use crate::models::customer_group_translations::{self, CreateParams, UpdateParams};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;

pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/customer-group-translations", post(create))
        .route("/customer-group-translations/:id", get(get_by_id))
        .route("/customer-group-translations/:id", post(update))
        .route("/customer-group-translations/:id/delete", post(delete))
        .route(
            "/customer-group-translations/by-group/:group_id",
            get(get_by_group),
        )
        .route(
            "/customer-group-translations/by-locale/:locale",
            get(get_by_locale),
        )
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let translation = customer_group_translations::Model::create(&state.db, params).await?;
    format::json(translation)
}

async fn get_by_id(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let translation = customer_group_translations::Model::find_by_id(&state.db, &id).await?;
    format::json(translation)
}

async fn update(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
    Json(params): Json<UpdateParams>,
) -> Result<Response> {
    let translation =
        customer_group_translations::Model::update_by_id(&state.db, &id, params).await?;
    format::json(translation)
}

async fn delete(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    customer_group_translations::Model::delete_by_id(&state.db, &id).await?;
    format::json(())
}

async fn get_by_group(
    State(state): State<AppContext>,
    axum::extract::Path(group_id): axum::extract::Path<String>,
) -> Result<Response> {
    let translations =
        customer_group_translations::Model::find_by_group(&state.db, &group_id).await?;
    format::json(translations)
}

async fn get_by_locale(
    State(state): State<AppContext>,
    axum::extract::Path(locale): axum::extract::Path<String>,
) -> Result<Response> {
    let translations =
        customer_group_translations::Model::find_by_locale(&state.db, &locale).await?;
    format::json(translations)
}
